import { BasePartExPlugin, GameEx, Plugin, PluginButton,ScriptEditorService, Selection, ToolBar } from "./plugints";

const pluginEx = plugin as Plugin | undefined
const gameEx = game as GameEx
const ChangeHistoryService = gameEx.GetService('ChangeHistoryService');
const SelectionEx = gameEx.GetService('Selection') as Selection;
const toolbar = pluginEx?.CreateToolbar('GenerCss') as ToolBar | undefined
export const newScriptButton =
    toolbar?.createButton('GenerCss', 'GenerCss', 'rbxassetid://4458901886') as PluginButton | undefined


if (newScriptButton) newScriptButton.ClickableWhenViewportHidden = true;

function click() {
    const SelectionEx = gameEx.GetService('Selection') as Selection;
        /**
         * 选中对象
         */
        const selectedInstances = SelectionEx.Get() as Instance[];
        if (selectedInstances.size() >= 1) {
            /**
             * 选中文件
             */
            const selectFirst = selectedInstances[0];
            const x = new Instance('ModuleScript');
            x.Name = selectFirst.Name
            x.Parent = game.GetService('Lighting');
            const scriptEditService = gameEx.GetService('ScriptEditorService') as ScriptEditorService
            let scriptString = ''
            const writeStartFunction = (node: Instance, start = true) => {
                const className = node.ClassName;
                const tag = className.lower();
                const key = node.Name
                if (start)
                    return `<${tag} {...s('${key}')}  Key={'${key}'}>
    `
                else
                    return `</${tag}>
    `
            }
            const readFunction = (node: Instance) => {
                scriptString += writeStartFunction(node)
                node.GetChildren().forEach(c => {
                    readFunction(c)
                })
                scriptString += writeStartFunction(node, false)
            }
            readFunction(selectFirst)
            scriptEditService.UpdateSourceAsync(x, (o) => {
                return scriptString
            })
        } else {
            throw ('you need select some mesh or folder/model')
        }

}
newScriptButton?.Click.Connect(click)